package me.zhengjie.modules.weixin.callback;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import me.zhengjie.utils.enums.OrderPrefixEnum;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("wechat/pay")
public class OrderPayController {
    private static final Logger log = LoggerFactory.getLogger(OrderPayController.class);

    @Autowired
    private WxPayService wxPayService;

    /**
     * 支付成功回调
     * @return
     */
    @RequestMapping("callback")
    public String callbackV2(HttpServletRequest request, HttpServletResponse response){
        //获取回调参数
        try {
            response.setContentType("text/xml");
            log.info("支付回调start======================");
            String xmlResult = null;
            try {
                xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            } catch (IOException e) {
                log.error("支付回调IOUtils.toString 异常",e);
            }
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlResult);
            log.info("支付回调WxPayOrderNotifyResult==========="+ JSON.toJSONString(notifyResult));
            if (Objects.isNull(notifyResult)){
                log.error("notifyResult is null");
                return WxPayNotifyResponse.fail("失败");
            }
            OrderPrefixEnum prefixEnum = OrderPrefixEnum.getInstance(notifyResult.getOutTradeNo());
            if (Objects.isNull(prefixEnum)){
                log.error("支付回调订单号前缀不匹配");
                return WxPayNotifyResponse.fail("失败");
            }
            boolean execute = PayCallbackFactory.prefix(prefixEnum).execute(notifyResult);
            if (!execute){
                return WxPayNotifyResponse.fail("失败");
            }
            return WxPayNotifyResponse.success("成功");
        } catch (WxPayException e) {
            log.info("支付回调异常",e);
        }
        return WxPayNotifyResponse.fail("失败");
    }
}
